<template>
  <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleTab">
      <el-tab-pane label="图片" name="image" />
      <el-tab-pane label="视频" name="video" />
   </el-tabs>
   <el-container class="library">
    <el-header class="header">
      <el-row>
        <el-col :span="18">
          <el-button type="primary" v-if="$filters.auth($filters.PrivilegeType.Add)" :icon="Upload" @click="handleUpload">上传{{ query.entity.type === FileType.Image ? '图片' :'视频' }}</el-button>
          <el-button @click="handleAdd" class="add" plain>添加分类</el-button>
        </el-col>
        <el-col :span="6">
          <el-input v-model="query.entity.name" placeholder="请输入名称" class="wd300" :prefix-icon="Search" maxlength="20" clearable @keyup.enter="loadFile" @clear="loadFile" />
        </el-col>
      </el-row>
    </el-header>
    <el-container>
      <el-aside>
          <div class="category">
            <ul>
              <li v-for="(item , index) in categorys" :class="{active: selectCategory.id === item.id }" @click="handleChangeCategory(item)" :key="index">
                <span class="name">{{ item.name }}</span>
                <span v-if="selectCategory.id !== item.id || index === 0" class="count">({{ item.fileCount }})</span>
                <span v-else class="operation">
                  <el-button @click="handleUpdate(item)" type="text"> <Edit class="editor pointer" /> </el-button>
                  <el-popconfirm :width="300" @confirm="handleDeleteCategory(item.id)" title="确定要删除吗?仅删除分组，不删除图片，组内图片将自动归入未分组">
                    <template #reference>
                      <el-button type="text"> <Delete class="delete pointer" /></el-button>
                    </template>
                  </el-popconfirm>
                </span>
              </li>
            </ul>
          </div>
        </el-aside>
        <el-main class="list">
          <div class="title">
            <span class="name">{{ selectCategory.name }}</span>
          </div>
          <div class="filelist">
            <el-checkbox-group v-model="checkeds" @change="handleCheckedItemsChange">
              <ul>
                <li v-for="item of list" :key="item.id">
                 <el-image v-if="query.entity.type === FileType.Image" :src="commonStore.setting.fileDomain + item.path" fit="scale-down" :preview-src-list="[commonStore.setting.fileDomain + item.path]" />
                  <el-image v-else :src="commonStore.setting.fileDomain + item.cover" fit="scale-down" @click="handleViewVideo(item)" />
                  <el-checkbox :label="item.id" :key="item.id" />
                  <ZoomIn v-if="query.entity.type === FileType.Image" class="icon-zoom" />
                  <View v-else class="icon-zoom" />
                  <p> {{ item.name }}</p>
                  <el-button-group>
                    <el-button type="text" @click="handleUpdateFileName(item)">改名</el-button>
                    <el-button type="text" @click="handleUpdateFileCategory(item)">分组</el-button>
                    <el-button type="text" @click="handleDeleteFile(item.id)">删除</el-button>
                  </el-button-group>
                </li>
              </ul>
            </el-checkbox-group>
          </div>
          <footer v-if="total" class="filefooter">
            <div class="operation">
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
              <el-button class="updatefile" @click="handleBatchUpdateFileCategory">修改分组</el-button>
              <el-button class="deletefile" @click="handleDeleteFile(0)">批量删除</el-button>
            </div>
            <div class="pagination">
              <el-pagination background @current-change="handleCurrentChange" v-model:current-page="query.page.index" :page-size="query.page.size" layout="total,prev,pager, next" :total="total" />
            </div>
          </footer>
        </el-main>
    </el-container>
   </el-container>
   <image-upload v-model:visible="imageVisible" v-model:category="query.entity.categoryId"  @on-confirm="onImageConfirm" />
   <video-upload v-model:visible="videoVisible" v-model:category="query.entity.categoryId"  @on-confirm="onVideoConfirm" />
   <!--添加分类-->
   <el-dialog append-to-body v-model="categoryForm.dialogVisible" :title="categoryForm.title" width="400px">
      <el-form ref="categoryFormRef" label-width="150px" class="ruleForm" :model="categoryForm.form" :rules="categoryForm.rules">
        <el-form-item label="分类名称：" prop="name">
          <el-col :span="22">
            <el-input v-model="categoryForm.form.name" maxlength="6" show-word-limit placeholder="最多可输入6个字符" />
          </el-col>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryForm.dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCategorySave(categoryFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!--添加分类 end-->
    <!--编辑图片名称-->
    <el-dialog append-to-body v-model="updateFileNameForm.dialogVisible" :title="updateFileNameForm.title" width="400px">
      <el-form ref="updateFileNameFormRef" label-width="150px" class="ruleForm" :model="updateFileNameForm.form" :rules="updateFileNameForm.rules">
        <el-form-item label="名称：" prop="name">
          <el-col :span="22">
            <el-input v-model="updateFileNameForm.form.name" show-word-limit placeholder="请输入名称" />
          </el-col>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateFileNameForm.dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleFileUpdateNameSave(updateFileNameFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!--编辑图片名称 end-->
     <!--修改图片分类-->
     <el-dialog append-to-body v-model="updateFileCategoryForm.dialogVisible" :title="updateFileCategoryForm.title" width="400px">
      <el-form ref="updateFileCategoryFormRef" label-width="150px" class="ruleForm" :model="updateFileCategoryForm.form" :rules="updateFileCategoryForm.rules">
        <el-form-item label="分类：" prop="categoryId">
          <el-col :span="22">
            <el-select v-model="updateFileCategoryForm.form.categoryId" placeholder="Select">
              <el-option v-for="item in categorys" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-col>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateFileCategoryForm.dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleFileUpdateCategorySave(updateFileCategoryFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!--修改图片分类 end-->
    <!--查看视频-->
    <el-dialog  width="600px" v-model="viewVideoForm.dialogVisible">
    <video style="max-width:560px" controls :src="commonStore.setting.fileDomain  + viewVideoForm.form.path" :autoplay="true"></video>
    </el-dialog>
    <!--查看视频 end-->
</template>
<script lang="ts" setup>
import { Upload,Search,Edit,Delete,ZoomIn,View} from '@element-plus/icons-vue'
import  ImageUpload from '@/components/File/ImageUpload.vue'
import  VideoUpload from '@/components/File/VideoUpload.vue'
import {FileCategorys,Files,FileCategoryRemove, FileCategorySave, FileRemove, SetFileName,SetFileGroup} from '@/api/file'
import { ref,onMounted } from 'vue'
import type { TabsPaneContext } from 'element-plus'
import { ElForm,ElMessage,ElMessageBox } from 'element-plus'
import { useCommonStore } from '@/stores/common'
import {FileType} from '@/utils/enum'
const commonStore  = useCommonStore()
const activeName = ref<string>('image')
/**
 * 查询条件
 */
const query =ref<PageModel<FileQuery>>({
  orderbyName: '',
  isAsc: false,
  beginDateTime: '',
  endDateTime: '',
  entity: {
    type: FileType.Image,
    name: '',
    categoryId: 0
  },
  page: {
      index: 1,
      size: 12
  }
})

const imageVisible = ref<boolean>(false)
const videoVisible = ref<boolean>(false)
const categorys = ref<FileCategory[]>([])
const list = ref<FileView[]>([])
const total = ref<number>(0)
const selectCategory = ref<any>({
    id :0,
    name:'未分组'

})

///选中图片
const checkeds = ref<any>([])
const isIndeterminate = ref<boolean>(false)//半选
const checkAll = ref<boolean>(false)//是否全选
/**
 * 编辑框
 */
const updateFileNameForm = ref({
  dialogVisible: false,
  title:'修改名称',
  form: {
      id : 0,
      name:''
  },
  rules:{
      name: [{ required: true, message: '请输入图片名称', trigger: 'blur' }]
  }
})

/**
 * 添加分类
 */
const categoryForm = ref<DialogForm<FileCategory>>({
   dialogVisible: false,
   title:'添加分类',
   form: {
    id : 0,
    type : query.value.entity.type,
    name :'',
    fileCount: 0
   },
    rules: {
      name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
    }
})

/**
 * 分组
 */
const updateFileCategoryForm = ref<DialogForm<BatchEdior>>({
  dialogVisible: false,
  title:'修改分组',
  form: {
        ids : [],
        categoryId:0,
        type:query.value.entity.type,
    },
    rules:{
        categoryId: [{ required: true, message: '请选择分类', trigger: 'blur' }]
    }
})

type FormInstance = InstanceType<typeof ElForm>
const categoryFormRef = ref<FormInstance>()
const updateFileNameFormRef = ref<FormInstance>() //修改名称
const updateFileCategoryFormRef = ref<FormInstance>() //修改分类
const viewVideoForm = ref <DialogForm<FileView>>(
  {
    dialogVisible: false,
    title:'查看视频',
    form: {
      id: 0,
      categoryId: 0,
      cover: '',
      name: '',
      size:0,
      path: ''
    }
  }
)

const handleTab =(tab: TabsPaneContext, event: Event):void => {
  if(tab.paneName === 'image')
    query.value.entity.type = FileType.Image
  else
    query.value.entity.type = FileType.Video
    categoryForm.value.form.type = query.value.entity.type
    selectCategory.value = {
      id :0,
      name:'未分组'
    }
    loadCategory()
    loadFile()
}
/**
 * 上传
 */
const handleUpload = ():void => {
  if(query.value.entity.type == FileType.Image)
    imageVisible.value = true
  else
    videoVisible.value = true
}
/**
 * 加载列表
 */
const loadFile = ():void => {
  Files(query.value).then((res:ServiceResponse<FileView[]>) => {
    if(res.success) {
      list.value = res.data ?? []
      total.value = res.count ?? 0

    }
  })
}
/**
 * 图片上传成功
 * @param list 
 */
const onImageConfirm = (list:FileEditor[]):void => {
  imageVisible.value = false
  query.value.page.index = 1
  loadCategory()
  loadFile()
}
/**
 * 视频上传成功
 * @param list 
 */
const onVideoConfirm = (list:FileEditor):void => {
  videoVisible.value = false
  query.value.page.index = 1
  loadCategory()
  loadFile()
}
/**
 * 加载分类
 */
const loadCategory = ():void => { 
  FileCategorys(query.value.entity.type).then((res:ServiceResponse<FileCategory[]>) => {
    categorys.value = res.data ?? []
  })
}
/**
 * 切换分类
 * @param item 
 */
const handleChangeCategory = (item:FileCategory):void => {
  selectCategory.value.id = item.id
  selectCategory.value.name = item.name
  query.value.entity.categoryId =  item.id
  clearCheck()
  loadFile()
}
/**
 * 清除选中
 * @param item 
 */
const clearCheck = ():void => {
    checkAll.value = false
    isIndeterminate.value = false
    checkeds.value = []
}
/**
 * 弹出修改名称
 * @param item 
 */

const handleUpdateFileName = (item :any) => {
  updateFileNameForm.value.dialogVisible = true
  updateFileNameForm.value.form.id = item.id
  updateFileNameForm.value.form.name = item.name
}

const handleAdd = () : void => {
  categoryForm.value.title ='添加分类'
  categoryForm.value.dialogVisible = true
  categoryForm.value.form.id = 0
  categoryForm.value.form.name = ''
}

/**
 * 添加编辑分类名称
 */
const handleUpdate = (row:FileCategory) : void => {
  categoryForm.value.title ='编辑分类'
  categoryForm.value.dialogVisible = true
  categoryForm.value.form.id = row.id
  categoryForm.value.form.name = row.name
}

/**
 * 删除分类
 */
const handleDeleteCategory = (id:number) :void => {
  FileCategoryRemove(id).then((res:any) =>{
   if (res.success) {
       loadCategory()
        query.value.page.index =1
        query.value.entity.categoryId = 0
        selectCategory.value.id = 0
        selectCategory.value.name = '未分组'
        loadFile()
        ElMessage.success('删除成功')
      } else return ElMessage.error(res.msg)
 })
}

/**
 * 保存分类
 */
const handleCategorySave = (formEl: FormInstance | undefined): void => {
 if (!formEl) return
 formEl.validate((valid) => {
   if (valid) {
    FileCategorySave(categoryForm.value.form).then((res: any) => {
        if (res.success) {
        categoryForm.value.dialogVisible = false
        ElMessage.success('操作成功')
          loadCategory()
        } else {
        return ElMessage.error(res.msg)
        }
      })
   }
 })
}

/** 全选 */
const handleCheckedItemsChange = (value:string[]):void => {
  if(value.length > 0)
  {
    checkAll.value =  (value.length === list.value.length)
    isIndeterminate.value = (value.length !== list.value.length)
  }
  else
  {
    checkAll.value = false
    isIndeterminate.value = false
  }
}
/**
 * 弹出修改分类
 * @param item 
 */
const handleUpdateFileCategory = (item : any):void => {
  updateFileCategoryForm.value.dialogVisible =true
  updateFileCategoryForm.value.form.ids =[item.id]
  updateFileCategoryForm.value.form.categoryId = item.categoryId
}
/**
 * 删除分组
 */
const handleDeleteFile =(id : number):void => {

  let ids:number[] = []
  if(id > 0) {
    ids.push(id)
  }
  else {
      if(checkeds.value.length === 0 ) {
        ElMessage.error(`请选择${query.value.entity.type === FileType.Image ? '图片':'视频'}`)
        return
      }
      ids = checkeds.value
  }
  updateFileCategoryForm.value.form.ids = ids
  ElMessageBox.confirm(
    '确定要删除吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    FileRemove(updateFileCategoryForm.value.form).then((res:any) => {
      if (res.success) {
        ElMessage.success('操作成功')
        loadCategory()
        loadFile()
      } else ElMessage.error(res.msg)
    })
  })
  .catch(() => {})
}

const handleCheckAllChange =(val:Boolean) => {
     let checkedItems: number[] = []
     list.value.map((item:FileView) => { checkedItems.push(item.id)})
     checkeds.value = val ? checkedItems : []
}

//分页
const handleCurrentChange = (currentPage:number):void => {
    query.value.page.index = currentPage 
    loadFile()
}

/** 
 * 批量修改分类
 */
const handleBatchUpdateFileCategory = ():void => {
 if(checkeds.value.length === 0 )  {

  ElMessage.error(`请选择${query.value.entity.type === FileType.Image ? '图片':'视频'}`)
  return
 }
   updateFileCategoryForm.value.dialogVisible = true
  updateFileCategoryForm.value.form.ids = checkeds.value
  updateFileCategoryForm.value.form.categoryId = selectCategory.value.id
  updateFileCategoryForm.value.form.categoryId = 0
}

/**
 * 修改文件名称
 */
const handleFileUpdateNameSave =  (formEl: FormInstance | undefined): void => {
 if (!formEl) return
 formEl.validate((valid) => {
   if (valid) {
    SetFileName(updateFileNameForm.value.form.id, updateFileNameForm.value.form.name).then((res:any) => {
       if (res.success) {
        ElMessage.success('操作成功')
        updateFileNameForm.value.dialogVisible = false
          loadFile()
      } else ElMessage.error(res.msg)
    })
   }
 })
}

/**
 * 修改分类
 */
const handleFileUpdateCategorySave =  (formEl: FormInstance | undefined): void => {
 if (!formEl) return
 formEl.validate((valid) => {
   if (valid) {
    SetFileGroup(updateFileCategoryForm.value.form).then((res:any) => {
       if (res.success) {
        ElMessage.success('操作成功')
        updateFileCategoryForm.value.dialogVisible = false
        loadCategory()
        loadFile()
      } else ElMessage.error(res.msg)
    })
   }
 })
}
const handleViewVideo = (item:FileView):void => {
  viewVideoForm.value.dialogVisible = true
  viewVideoForm.value.form = item
}


onMounted(() => {
  
  if(!commonStore.setting.fileDomain)
    commonStore.getSetting().then((res:SiteSetting) => {
       
    })
    loadCategory()
    loadFile()
})

</script>

<style lang="scss" scoped>
@import "@/assets/styles/mixin.scss";
@import "@/assets/styles/formPage.scss";
.library {
  height: calc(100vh - 230px);
  .header {
    height: 60px;
    line-height: 60px;
  }
}
.el-aside {
  width: 210px;
  
}
.category{
  width: 100%;
  display: flex;
  flex-direction:column;
  justify-content:center;
  ul {
    padding: 0;
    margin: 0;
    background-color: rgba(27,50,71,.04);
    border-radius: 4px;
    height: calc(100vh - 320px);
    //overflow-y: scroll;
    li {
        padding: 12px 8px;
        display: flex;
        justify-content:space-between;
        .name {
          text-align: left;
        }
        .count {
        text-align: right;
        } 
        .operation {
          text-align: right;
          .delete {
           width: 1em; 
           height: 1em; 
          }
          .editor { 
             width: 1em; 
             height: 1em; 
             margin-right: 5px;
            }
        }     
    }
    .active {
      background-color: #e6f7ff;
      color: #1890ff;
    }
  }
 
}
.list {
  margin-left: 20px;
  .title{
    .operation {
      color: #1890ff;
      margin-left: 5px;
    }
  }
}
.pointer {
  cursor:pointer;
}
.filelist{
         height: calc(100vh - 370px);
          margin-top: 20px;
          overflow-y: scroll;
          flex: 1;
          overflow-x: hidden;
          ul {
            display: flex;
            flex-wrap: wrap;
            margin-left: -16px;
            li {
              flex: 0 0 calc(16.6667% - 16px);
              margin-left: 16px;
              margin-bottom: 16px;
              position: relative;
              overflow-y: hidden;
              border: 1px solid #f0f0f0;
              box-sizing: border-box;
              .active {
                border: 1px solid #1890ff;
              }
              .el-image {
                width: 100%;
                height: 152px;
              }
              .el-checkbox {
                position: absolute;
                top: 32px;
                right: 0;
                bottom: 70px;
                left: 0;
                height: auto;
                border-radius: 0;
                padding: 0;
                .el-checkbox__input {
                  position: absolute;
                  top: 8px;
                  right: 8px;
                }
              }
              .icon-zoom {
                width: 1em;
                height: 1em;
                display: none;
                background: rgba(0, 0, 0, 0.04);
                position: absolute;
                left: 0;
                top: 0;
                font-size: 24px;
                padding: 4px;
                pointer-events: none;
                cursor: pointer;
                color: #8d8d8d;
              }
              &:hover .icon-zoom {
                display: block;
              }
              ::v-deep .el-checkbox {
                .el-checkbox__input {
                  position: absolute;
                  right: 8px;
                  top: -20px;
                }
                .el-checkbox__label {
                  position: absolute;
                  left: 32px;
                  top: -32px;
                  height: 32px;
                  right: 0;
                  font-size: 0;
                }
              }
              p {
                font-size: 14px;
                line-height: 36px;
                text-align: center;
                text-overflow: ellipsis;
                white-space: nowrap;
                overflow: hidden;
                padding: 0 8px;
                // position: absolute
                // left: 0
                // right: 0
                // bottom: 36px
                // background-color: rgba(0, 0, 0, 0.04)
              }
              .el-button-group {
                height: 36px;
                line-height: 36px;
                display: flex;
                align-items: center;
                justify-content: space-between;
              }
            }
          }
}
.filefooter{
  display: flex;
  justify-content:space-between;
  .operation {
    display: flex;
    width: 300px;
    align-items:center;
    .updatefile {
      margin-left: 10px;
     }
     .deletefile {
      margin-left: 10px;
     }
  }
}
</style>
